package com.ytc.content.service.impl;

import com.ytc.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

@Component
public class PublishHtmlService {
    @Autowired
    private MinioProperties properties;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioClient client;
    @Async
    public void publish(Map<String,Object> map, Long coursePubId) throws Exception{
        //5.页面静态化
        //5.1构建Configuration对象
        //5.2指定字符集编码指定模板位置
        //5.3通过Configuration获取指定模板
        Template template = configuration.getTemplate("learing_article.ftl");
        //5.4根据数据和模板，调用工具，获取静态页面字符串
        String html  = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
        //5.5构建输入流
        ByteArrayInputStream stream = new ByteArrayInputStream(html.getBytes());
        //6.存入minio
        //6.1准备文件名称
        String path = "/pages/"+coursePubId+".html";
        //6.2构造PutObjects
        PutObjectArgs build = PutObjectArgs.builder()
                .contentType("text/html")
                .stream(stream, stream.available(), -1)
                .bucket(properties.getBucket())
                .object(path)
                .build();
        //调用minio上传
        client.putObject(build);
    }

}
